package com.edooschool.oral.arithmetic.web.controller;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.entity.cfg.JsConfig;
import com.edooschool.entity.oral.OralAnswerRecord;
import com.edooschool.entity.oral.OralQuestion;
import com.edooschool.entity.oral.OralRound;
import com.edooschool.oral.arithmetic.entity.OralRoundResult;
import com.edooschool.oral.arithmetic.processor.WechatProcessor;
import com.edooschool.oral.arithmetic.service.OralService;
import com.edooschool.oral.arithmetic.web.interceptor.UserContext;
import com.edooschool.oral.arithmetic.web.interceptor.UserContextType;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("")
@UserContext(type = UserContextType.WECHAT_BASE)
public class OralController {
    
    @Autowired
    private WechatProcessor wechatProcessor;
    
    @Autowired
    private OralService oralService;
    
    private static final String OPENID_KEY = "edooschool-wechat-openid";
    
    /**
     * 
     * @param request
     * @return
     */
    @UserContext(type = UserContextType.WECHAT_BASE)
    @RequestMapping(value = {"/home", "/"}, method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("oral/oral-index");
        
        int userCount = oralService.countUser();
        modelAndView.addObject("userCount", userCount);
        
        
        String curl = com.demo2do.core.web.utils.WebUtils.getRealRequestURL(request);
        JsConfig jsConfig = wechatProcessor.generateJsConfig(curl);
        modelAndView.addObject("jsConfig", JsonUtils.toJson(jsConfig));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param groupId
     * @param request
     * @return
     */
    @UserContext(type = UserContextType.WECHAT_BASE)
    @RequestMapping(value = "/oral-groups/{groupId}", method = RequestMethod.GET)
    public ModelAndView list(@PathVariable("groupId") Long groupId,
                             HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("oral/oral-list");
        
        Cookie openidCookie =WebUtils.getCookie(request, OPENID_KEY);
        
        if(openidCookie == null) {
            modelAndView.setViewName("redirect:/error");
            return modelAndView;
        }
        
        String curl = com.demo2do.core.web.utils.WebUtils.getRealRequestURL(request);
        JsConfig jsConfig = wechatProcessor.generateJsConfig(curl);
        modelAndView.addObject("jsConfig", JsonUtils.toJson(jsConfig));
        
        List<OralRound> oralRounds = oralService.listOralRound(groupId);
        modelAndView.addObject("oralRounds", oralRounds);
        
        String openid = openidCookie.getValue();
        List<OralAnswerRecord> oralAnswerRecords = new LinkedList<>();
        oralAnswerRecords = oralService.listOralAnswerRecord(openid);
        
        Map<String, List<OralAnswerRecord>> records = CollectionUtils.constructMapValues(oralAnswerRecords, "oralRound.id");
        modelAndView.addObject("records", records);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param request
     * @return
     */
    @UserContext(type = UserContextType.WECHAT_BASE)
    @RequestMapping(value = "/oral-answer-records", method = RequestMethod.GET)
    public ModelAndView records(HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("oral/oral-record-list");
        
        Cookie openidCookie =WebUtils.getCookie(request, OPENID_KEY);
        
        if(openidCookie == null) {
            modelAndView.setViewName("redirect:/error");
            return modelAndView;
        }
        
        String curl = com.demo2do.core.web.utils.WebUtils.getRealRequestURL(request);
        JsConfig jsConfig = wechatProcessor.generateJsConfig(curl);
        modelAndView.addObject("jsConfig", JsonUtils.toJson(jsConfig));
        
        String openid = openidCookie.getValue();
        List<OralAnswerRecord> oralAnswerRecords = oralService.listOralAnswerRecord(openid);
        
        modelAndView.addObject("records", oralAnswerRecords);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param roundId
     * @param request
     * @return
     */
    @UserContext(type = UserContextType.WECHAT_BASE)
    @RequestMapping(value = "/rounds/{roundId}", method = RequestMethod.GET)
    public ModelAndView oralRound(@PathVariable("roundId") Long roundId, HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("oral/oral-view");
        
        Cookie openidCookie =WebUtils.getCookie(request, OPENID_KEY);
        
        if(openidCookie == null) {
            modelAndView.setViewName("redirect:/error");
            return modelAndView;
        }
        
        OralRound oralRound = oralService.loadOralRound(roundId);
        
        if(oralRound == null) {
            modelAndView.setViewName("redirect:/home");
            return modelAndView;
        }
        
        String curl = com.demo2do.core.web.utils.WebUtils.getRealRequestURL(request);
        JsConfig jsConfig = wechatProcessor.generateJsConfig(curl);
        modelAndView.addObject("jsConfig", JsonUtils.toJson(jsConfig));
        
        String openid = openidCookie.getValue();
        List<OralAnswerRecord> oralAnswerRecords = oralService.listOralAnswerRecord(openid, oralRound.getId());
        modelAndView.addObject("records", oralAnswerRecords);
        
        List<OralQuestion> questions = oralService.listQralQuestion(oralRound);
        
        modelAndView.addObject("round", oralRound);
        modelAndView.addObject("roundString", JsonUtils.toJson(oralRound));
        modelAndView.addObject("questions", JsonUtils.toJson(questions));
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param roundId
     * @param result
     * @param request
     * @return
     */
    @UserContext(type = UserContextType.WECHAT_BASE)
    @RequestMapping(value = "/rounds/{roundId}", method = RequestMethod.POST)
    public ModelAndView result(@PathVariable("roundId") Long roundId,
                               OralRoundResult result,
                               HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("oral/oral-result");
        
        Cookie openidCookie =WebUtils.getCookie(request, OPENID_KEY);
        
        if(openidCookie == null) {
            modelAndView.setViewName("redirect:/error");
            return modelAndView;
        }
        
        String openid = openidCookie.getValue();
        
        OralRound round = oralService.loadOralRound(roundId);
        OralAnswerRecord record = oralService.saveOralAnswer(round, result, openid);
        
        modelAndView.addObject("record", record);
        
        String curl = com.demo2do.core.web.utils.WebUtils.getRealRequestURL(request);
        JsConfig jsConfig = wechatProcessor.generateJsConfig(curl);
        modelAndView.addObject("jsConfig", JsonUtils.toJson(jsConfig));
        
        return modelAndView;
    }
    
    /**
     * 
     * @param recordId
     * @param request
     * @return
     */
    @UserContext(type = UserContextType.WECHAT_BASE)
    @RequestMapping(value = "/rounds/{roundId}/records/{recordId}", method = RequestMethod.GET)
    public ModelAndView oralRoundRecord(@PathVariable("recordId") Long recordId, HttpServletRequest request) {
        

        ModelAndView modelAndView = new ModelAndView("oral/oral-report");
        
        Cookie openidCookie =WebUtils.getCookie(request, OPENID_KEY);
        if(openidCookie == null) {
            modelAndView.setViewName("redirect:/error");
            return modelAndView;
        }
        
        OralAnswerRecord oralAnswerRecord = oralService.loadOralAnswerRecord(recordId);
        if(oralAnswerRecord == null) {
            modelAndView.setViewName("redirect:/home");
            return modelAndView;
        }
        
        modelAndView.addObject("oralAnswerRecord", oralAnswerRecord);
        
        String curl = com.demo2do.core.web.utils.WebUtils.getRealRequestURL(request);
        JsConfig jsConfig = wechatProcessor.generateJsConfig(curl);
        modelAndView.addObject("jsConfig", JsonUtils.toJson(jsConfig));
        
        OralRoundResult result = JsonUtils.parse(oralAnswerRecord.getDetail(), OralRoundResult.class);
        modelAndView.addObject("result", result);
        
        return modelAndView;
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/oral/stat", method = RequestMethod.GET)
    public ModelAndView stat() {
        
        ModelAndView modelAndView = new ModelAndView("oral/oral-stat");
        
        modelAndView.addObject("recordTotal", oralService.countRecord());
        modelAndView.addObject("userTotal", oralService.countUser());
        modelAndView.addObject("shareTotal", oralService.countShare());
        
        return modelAndView;
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/oral-waiting", method = RequestMethod.GET)
    public String waiting() {
        return "oral/oral-waiting";
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String error() {
        return "error-page";
    }
}

